package com.elinkway.infinitemovies.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.bean.CjspUserInfo;
import com.elinkway.infinitemovies.bean.JumpData;
import com.elinkway.infinitemovies.bean.UserLoginBean;
import com.elinkway.infinitemovies.bigdata.BigDataUtils;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.UserLoginParser;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.SelfDataConstant;
import com.elinkway.infinitemovies.selfdata.bean.LoginDataRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.ui.activity.commonwebview.CommonWebViewActivity;
import com.elinkway.infinitemovies.utils.IdUtils;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.MoviesUtils;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoDataHull;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.Config;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

/**
 * Author: liuxiaojiang(liuxiaojiang@lvideo.com)
 * Date: 2016-03-09
 * Time: 12:07
 * Description: FIXME
 */
public class LoginActivity extends BaseSecondaryActivity implements View.OnClickListener {

    public static final String TAG = "LoginActivity";

    public static final String EVENT_LOGIN_FAILED = "login_failed";

    private RelativeLayout weixinLay;
    private RelativeLayout QQLay;
    private RelativeLayout weiboLay;
    private UMShareAPI mShareAPI;
    private SharedPreferences mLoginSp;
    public final static String USERIMAGEURL = "imageUrl";
    public final static String USERGENDER = "gender";
    public final static String USERNICKNAME = "nickname";
    public final static String TOKEN = "token";     //调用登录接口返回的token
    public final static String UID = "uid";     // 登录接口返回的uid
    private String type;
    private String name;
    private String openId;
    private String gender = "2";
    private String photo;
    private String oldUid; // 原来登录用户的uid
    private TextView mLoginPrivacy;

    public static final String LOGINRESULT = "result";
    public static final int LOGINSUCCESS = 200;
    public static final int LOGINERROR = -1;
    public static final int LOGINCODE = 1999;
    private String from;
    LoginDataRecord mRecord;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Utils.isMonkeyRunning()) {
            finish();
            return;
        }
        super.setActionBarActivityClassName(TAG);
        initActionBar();
        mHandler = new Handler();
        Bundle extras = getIntent().getExtras();
        if(extras != null){
            from = extras.getString("from");
        }
        mTitleTv.setText("登录");
        setContentView(R.layout.activity_login);
        init();

        /**
         * 登录页曝光次数
         */
        LoginDataRecord loginDataRecord = MyDataRecordCreater.build(LoginDataRecord.class);
        loginDataRecord.setCur_url("page_login");
        loginDataRecord.setAcode("41");
        loginDataRecord.setRef_url("page_uc");
        RealmDaoManager.addMyDataRecord(loginDataRecord);

        mLoginSp = getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);
        mRecord = MyDataRecordCreater.build(LoginDataRecord.class);
        mRecord.setAcode("0");
        mRecord.setCur_url("page_login");
        mRecord.setRef_url("page_uc");
    }

    private void init() {
        weixinLay = (RelativeLayout) findViewById(R.id.weixin_login_rl);
        weixinLay.setOnClickListener(this);
        boolean showWechatLogin = false;
        if (!MoviesUtils.isProductKuaiKan()) {
            showWechatLogin = true;
        }
        weixinLay.setVisibility(showWechatLogin ? View.VISIBLE : View.GONE);
        QQLay = (RelativeLayout) findViewById(R.id.qq_login_rl);
        QQLay.setOnClickListener(this);
        weiboLay = (RelativeLayout) findViewById(R.id.weibo_login_rl);
        weiboLay.setOnClickListener(this);
        mShareAPI = UMShareAPI.get(MoviesApplication.getInstance());
        mLoginPrivacy = (TextView) findViewById(R.id.tv_login_privacy);
        mLoginPrivacy.setOnClickListener(this);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LoginDataRecord loginDataRecord = MyDataRecordCreater.build(LoginDataRecord.class);
            loginDataRecord.setCur_url("page_login");
            loginDataRecord.setRef_url("page_uc");
            loginDataRecord.setAcode("0");
            loginDataRecord.setAction("login_back_btn");
            RealmDaoManager.addMyDataRecord(loginDataRecord);
            LogUtils.d(TAG, "-----登录页面返回键监听-------");
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onClick(View view) {
        SHARE_MEDIA platform = null;
        switch (view.getId()){
            case R.id.weixin_login_rl:
                platform = SHARE_MEDIA.WEIXIN;
                UmengEventPoster.doEventPost(UmengEventPoster.CLICK_WEIXIN_LOGIN);
                // 获取原来登录的uid
                if (MoviesUtils.isProductCjsp()) {
                    oldUid = getOldUid();
                }
                mRecord.setAction("wechat_btn");
                break;
            case R.id.qq_login_rl:
                platform = SHARE_MEDIA.QQ;
                UmengEventPoster.doEventPost(UmengEventPoster.CLICK_QQ_LOGIN);
                mRecord.setAction("qq_btn");
                break;
            case R.id.weibo_login_rl:
                platform = SHARE_MEDIA.SINA;
                UmengEventPoster.doEventPost(UmengEventPoster.CLICK_WEIBO_LOGIN);
                mRecord.setAction("weibo_btn");
                break;
            case R.id.tv_login_privacy:
                Intent intent = new Intent();
                JumpData jumpData = new JumpData();
                Bundle jumpbundle = new Bundle();
                jumpData.setPlayUrl(IdUtils.PRIVACY_LINK);
                jumpData.setName(getString(R.string.law_clause));
                intent.setClass(this, CommonWebViewActivity.class);
                jumpbundle.putSerializable(Utils.CHANNEL_DTAT, jumpData);
                intent.putExtras(jumpbundle);
                intent.putExtra("id", R.drawable.law_clause);
                startActivity(intent);
                break;
        }
        if (MoviesUtils.isProductCjsp()) {
            Config.REDIRECT_URL = IdUtils.WEIBO_REDIRECT_URL;
        }
        mShareAPI.doOauthVerify(this, platform, umAuthListener);
    }

    public static void launch(Activity activity, String from) {
        Intent intent = new Intent(activity, LoginActivity.class);
        intent.putExtra("from", from);
        activity.startActivity(intent);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mShareAPI.onActivityResult(requestCode, resultCode, data);
    }

    //授权回调的监听
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(getApplicationContext(), "授权成功", Toast.LENGTH_SHORT).show();
            if(data != null){
                if(platform == SHARE_MEDIA.WEIXIN){
                    SharedPreferences.Editor editor = mLoginSp.edit();
                    editor.putString("loginType", "weixin");
                    editor.putString("openId", data.get("openid"));
                    editor.putString("accessToken", data.get("access_token"));
                    editor.commit();
                    type = "1";
                    openId = data.get("openid");
                }else if(platform == SHARE_MEDIA.QQ){
                    SharedPreferences.Editor editor = mLoginSp.edit();
                    editor.putString("loginType", "qq");
                    editor.putString("openId", data.get("openid"));
                    editor.putString("accessToken", data.get("access_token"));
                    editor.commit();
                    type = "2";
                    openId = data.get("openid");
                }else if(platform == SHARE_MEDIA.SINA){
                    SharedPreferences.Editor editor = mLoginSp.edit();
                    editor.putString("loginType", "weibo");
                    editor.putString("openId", data.get("uid"));
                    editor.putString("accessToken", data.get("access_token"));
                    editor.commit();
                    type = "3";
                    openId = data.get("uid");
                }else{

                }
            }
            mShareAPI.getPlatformInfo(LoginActivity.this, platform, umInfoListener);
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText( getApplicationContext(), "授权失败", Toast.LENGTH_SHORT).show();
            if(platform != null){
                if(platform == SHARE_MEDIA.WEIXIN){
                    mRecord.setRequestresult("api_wechat_failed");
                }else if(platform == SHARE_MEDIA.QQ){
                    mRecord.setRequestresult("api_qq_failed");
                }else if(platform == SHARE_MEDIA.SINA){
                    mRecord.setRequestresult("api_weibo_failed");
                }
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        RealmDaoManager.addMyDataRecord(mRecord);
                    }
                });
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText( getApplicationContext(), "授权取消", Toast.LENGTH_SHORT).show();
        }
    };

    //获取用户第三方信息的监听
    private UMAuthListener umInfoListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            if (data!=null){
//                Toast.makeText(getApplicationContext(), data.toString(), Toast.LENGTH_SHORT).show();
                if(platform == SHARE_MEDIA.WEIXIN){
                    String thirdGender = data.get("sex");
                    String thirdImage = data.get("headimgurl");
                    String thirdNickname = data.get("nickname");
                    SharedPreferences.Editor editor = mLoginSp.edit();
                    editor.putString(USERIMAGEURL, thirdImage);
                    editor.putString(USERGENDER, thirdGender);
                    editor.putString(USERNICKNAME, thirdNickname);
                    editor.commit();
                    name = thirdNickname;
                    photo = thirdImage;
                    gender = Utils.getWeiboGender(thirdGender);
                    mRecord.setRequestresult("api_wechat_succeed");
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            RealmDaoManager.addMyDataRecord(mRecord);
                        }
                    });
                    new RequestUserLoginTask(LoginActivity.this, "wechat").start();
                }else if(platform == SHARE_MEDIA.QQ){
                    String thirdGender = data.get("gender");
                    String thirdImage = data.get("profile_image_url");
                    String thirdNickname = data.get("screen_name");
                    SharedPreferences.Editor editor = mLoginSp.edit();
                    editor.putString(USERIMAGEURL, thirdImage);
                    editor.putString(USERGENDER, thirdGender);
                    editor.putString(USERNICKNAME, thirdNickname);
                    editor.commit();
                    name = thirdNickname;
                    photo = thirdImage;
                    gender = Utils.getQQGender(thirdGender);
                    mRecord.setRequestresult("api_qq_succeed");
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            RealmDaoManager.addMyDataRecord(mRecord);
                        }
                    });
                    new RequestUserLoginTask(LoginActivity.this, "qq").start();
                }else if(platform == SHARE_MEDIA.SINA){
                    String thirdGender = data.get("gender");
                    String thirdImage = data.get("profile_image_url");
                    String thirdNickname = data.get("screen_name");
                    SharedPreferences.Editor editor = mLoginSp.edit();
                    editor.putString(USERIMAGEURL, thirdImage);
                    editor.putString(USERGENDER, thirdGender);
                    editor.putString(USERNICKNAME, thirdNickname);
                    editor.commit();
                    name = thirdNickname;
                    photo = thirdImage;
                    gender = Utils.getWeiboGender(thirdGender);
                    mRecord.setRequestresult("api_weibo_succeed");
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            RealmDaoManager.addMyDataRecord(mRecord);
                        }
                    });
                    new RequestUserLoginTask(LoginActivity.this, "weibo").start();
                }else{

                }
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText( getApplicationContext(), "get fail", Toast.LENGTH_SHORT).show();
            if(platform != null){
                if(platform == SHARE_MEDIA.WEIXIN){
                    mRecord.setRequestresult("api_wechat_failed");
                }else if(platform == SHARE_MEDIA.QQ){
                    mRecord.setRequestresult("api_qq_failed");
                }else if(platform == SHARE_MEDIA.SINA){
                    mRecord.setRequestresult("api_weibo_failed");
                }
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        RealmDaoManager.addMyDataRecord(mRecord);
                    }
                });
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText( getApplicationContext(), "get cancel", Toast.LENGTH_SHORT).show();
        }
    };

    public String getOldUid() {
        SharedPreferences mySharedPreferences = this.getSharedPreferences(CjspUserInfo.TAG_LOGINFO,
                Context.MODE_PRIVATE);
        CjspUserInfo userInfo = new CjspUserInfo();
        if (mySharedPreferences.getBoolean(CjspUserInfo.TAG_ISLOGIN, false)) {
            String ujson = mySharedPreferences.getString(CjspUserInfo.TAG_IJSON, "");
            if (ujson != null) {
                userInfo = JSON.parseObject(ujson, CjspUserInfo.class);
                return userInfo.getUid();
            }
        }
        return null;
    }

    /**
     * 请求登录
     *
     */
    private class RequestUserLoginTask extends MoviesHttpAsyncTask<UserLoginBean> {

        String source;

        @Override
        public void netNull() {
            MobclickAgent.onEvent(LoginActivity.this, EVENT_LOGIN_FAILED, "LoginReport error netNull");
            if ("weibo".equals(source)) {
                mRecord.setRequestresult("uc_weibo_failed");
            } else if ("wechat".equals(source)) {
                mRecord.setRequestresult("uc_wechat_failed");
            } else if ("qq".equals(source)) {
                mRecord.setRequestresult("uc_qq_failed");
            }
            RealmDaoManager.addMyDataRecord(mRecord);
            super.netNull();
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            MobclickAgent.onEvent(LoginActivity.this, EVENT_LOGIN_FAILED, "LoginReport error dataNull netErr:" + updateId + " errMsg:" + errMsg);
            if ("weibo".equals(source)) {
                mRecord.setRequestresult("uc_weibo_failed");
            } else if ("wechat".equals(source)) {
                mRecord.setRequestresult("uc_wechat_failed");
            } else if ("qq".equals(source)) {
                mRecord.setRequestresult("uc_qq_failed");
            }
            RealmDaoManager.addMyDataRecord(mRecord);
            super.netErr(updateId, errMsg);
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            MobclickAgent.onEvent(LoginActivity.this, EVENT_LOGIN_FAILED, "LoginReport error dataNull:" + updateId + " errMsg:" + errMsg);
            if ("weibo".equals(source)) {
                mRecord.setRequestresult("uc_weibo_failed");
            } else if ("wechat".equals(source)) {
                mRecord.setRequestresult("uc_wechat_failed");
            } else if ("qq".equals(source)) {
                mRecord.setRequestresult("uc_qq_failed");
            }
            RealmDaoManager.addMyDataRecord(mRecord);
            super.dataNull(updateId, errMsg);
        }

        public RequestUserLoginTask(Context context, String source) {
            super(context);
            this.source = source;
        }

        @Override
        public LVideoDataHull<UserLoginBean> doInBackground() {
            LVideoDataHull<UserLoginBean> ret = MoviesHttpApi.userLoginRequest(
                    new UserLoginParser(), type, name, openId, gender, photo, oldUid);
            if (ret.getDataType() == LVideoDataHull.DataType.DATA_IS_INTEGRITY) {
                UserLoginBean v = ret.getDataEntity();
            }
            return ret;
        }

        @Override
        public void onPostExecute(int updateId, UserLoginBean result) {
            if(result != null){
                mLoginSp.edit().putString(TOKEN, result.getToken()).commit();
                mLoginSp.edit().putString(UID, result.getUid()).commit();
                MoviesApplication.isLoginDone = true;
                if("VideoDetailActivity".equals(from)){
                    LoginActivity.this.setResult(RESULT_OK, getIntent().putExtra(LOGINRESULT,LOGINSUCCESS));
                }
                LoginActivity.this.finish();
                MoviesConstant.isRefreshMyFragment = true;
                // 清除掉原来超级视频的信息
                if (MoviesUtils.isProductCjsp()) {
                    cleanCjspOldUserInfo();
                }
                if ("weibo".equals(source)) {
                    mRecord.setRequestresult("uc_weibo_succeed");
                } else if ("wechat".equals(source)) {
                    mRecord.setRequestresult("uc_wechat_succeed");
                } else if ("qq".equals(source)) {
                    mRecord.setRequestresult("uc_qq_succeed");
                }
                mRecord.setIlu(BigDataUtils.isLoginUser());
                RealmDaoManager.addMyDataRecord(mRecord);
            }else{
                if("VideoDetailActivity".equals(from)){
                    LoginActivity.this.setResult(RESULT_OK, getIntent().putExtra(LOGINRESULT,LOGINERROR));
                    LoginActivity.this.finish();
                }
                Toast.makeText( getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
                if ("weibo".equals(source)) {
                    mRecord.setRequestresult("uc_weibo_failed");
                } else if ("wechat".equals(source)) {
                    mRecord.setRequestresult("uc_wechat_failed");
                } else if ("qq".equals(source)) {
                    mRecord.setRequestresult("uc_qq_failed");
                }
                RealmDaoManager.addMyDataRecord(mRecord);
            }
        }

        @Override
        public void codeErr(String code, String msg) {
            MobclickAgent.onEvent(LoginActivity.this, EVENT_LOGIN_FAILED, "LoginReport error codeErr:" + code + " " + msg);
            if("VideoDetailActivity".equals(from)){
                LoginActivity.this.setResult(RESULT_OK, getIntent().putExtra(LOGINRESULT,LOGINERROR));
                LoginActivity.this.finish();
            }
            if(!TextUtils.isEmpty(msg)){
                Toast.makeText( getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText( getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
            }
            if ("weibo".equals(source)) {
                mRecord.setRequestresult("uc_weibo_failed");
            } else if ("wechat".equals(source)) {
                mRecord.setRequestresult("uc_wechat_failed");
            } else if ("qq".equals(source)) {
                mRecord.setRequestresult("uc_qq_failed");
            }
            RealmDaoManager.addMyDataRecord(mRecord);
        }
    }

    private void cleanCjspOldUserInfo() {
        SharedPreferences mySharedPreferences = this.getSharedPreferences(CjspUserInfo.TAG_LOGINFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySharedPreferences.edit();
        editor.clear();
        editor.commit();
    }
}
